package com.hxh.sync;

import java.util.concurrent.TimeUnit;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/9/9 23:10
 * 死锁 Demo
 */
public class DeadLock {

    static Object lockA = new Object();
    static Object lockB = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (lockA) {
                System.out.println("当前线程: " + Thread.currentThread().getName() + ", 持有锁 A");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lockB) {
                    System.out.println("当前线程: " + Thread.currentThread().getName() + ", 持有锁 B");
                }
            }
        }, "t1").start();

        new Thread(() -> {
            synchronized (lockB) {
                System.out.println("当前线程: " + Thread.currentThread().getName() + ", 持有锁 B");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lockA) {
                    System.out.println("当前线程: " + Thread.currentThread().getName() + ", 持有锁 A");
                }
            }
        }, "t2").start();
    }
}
